package com.fy.module.qu.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fy.common.dto.PageDto;
import com.fy.common.dto.PageResult;
import com.fy.module.qu.common.dto.QuPage;
import com.fy.module.qu.common.dto.QuSave;
import com.fy.module.qu.common.exception.ServiceException;
import com.fy.module.qu.common.vo.ApiRest;
import com.fy.module.qu.entity.Qu;
import com.fy.module.qu.entity.QuAnswer;
import com.fy.module.qu.entity.QuRepo;
import com.fy.module.qu.service.IQuAnswerService;
import com.fy.module.qu.service.IQuRepoService;
import com.fy.module.qu.service.impl.QuServiceImpl;
import com.fy.module.repo.entity.Repo;
import com.fy.module.repo.service.IRepoService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * <p>
 * 问题题目 前端控制器
 * </p>
 *
 * @author yiyi
 * @since 2023-03-21
 */
@RestController
@RequestMapping("/qu")
@Api(description = "题目管理模块")
@CrossOrigin
public class QuController {


    @Autowired
    private QuServiceImpl quService;

    @Autowired
    private IQuAnswerService answerService;

    @Autowired
    private IQuRepoService repoService;


    @PostMapping
    @ApiOperation("添加题目")
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public ApiRest insertQu(@RequestBody @ApiParam(value = "整合参数") QuSave quSave){
        System.out.println("quSave = " + quSave);
        return quService.insertQu(quSave);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除题目")
    @Transactional
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public ApiRest deleteQu(@ApiParam(value = "删除的id") @PathVariable String id){
        if (id == null || id.equals("")){
            throw new ServiceException("参数异常");
        }
        quService.removeById(id);
        UpdateWrapper<QuAnswer> quAnswerUpdateWrapper = new UpdateWrapper<>();
        quAnswerUpdateWrapper.eq("qu_id",id);
        answerService.remove(quAnswerUpdateWrapper);
        UpdateWrapper<QuRepo> quRepoUpdateWrapper = new UpdateWrapper<>();
        quRepoUpdateWrapper.eq("qu_id", id);
        repoService.remove(quRepoUpdateWrapper);
        return ApiRest.success();
    }

    @PutMapping()
    @ApiOperation("修改题目")
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public ApiRest updateQu(@RequestBody @ApiParam(value = "整合参数") QuSave quSave){
        return quService.updateQu(quSave);
    }

    @PostMapping("/page")
    @ApiOperation("题目分页")
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public PageResult selectPage(@RequestBody PageDto pageDto){
        PageResult pageResult = quService.selectPageQu(pageDto);
        return pageResult;
    }

    @GetMapping("/{id}")
    @ApiOperation("查询题目详情")
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public QuPage selectByid(@ApiParam(value = "") @PathVariable String id){
        QuPage quPage = quService.selectQuery(id);
        return quPage;
    }

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    @ApiOperation("上传图片")
    @PreAuthorize("hasAnyAuthority('student_add','student_list','course_list','course_add')")
    public String upload(@RequestParam("head") MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "abTMN413AarWspnnyPM39I1cqnpnbTqNkgEC5qoB";
        String secretKey = "GTRdScv3qO6pQ7rHYnB7msveWzOn89Xv3aHyjrMY";
        String bucket = "fy-exam-one";

//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        String tok = null;
        try {
            byte[] uploadBytes = file.getBytes();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSONUtil.toBean(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                key = putRet.hash;
                tok = upToken;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://rrwi9n5td.hn-bkt.clouddn.com/"+key;
    }

}
